package com.frozenc.controller.news;

import com.frozenc.domain.Comment;
import com.frozenc.domain.News;
import com.frozenc.domain.User;
import com.frozenc.mapper.CommentsMapper;
import com.frozenc.mapper.NewsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by FrozenC on 2016/9/12.
 */
@Controller
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsMapper newsMapper;

    @Autowired
    private CommentsMapper commentsMapper;

    @ModelAttribute
    public void setUser(HttpSession session, ModelMap modelMap){
        User user = (User) session.getAttribute("currUser");
        modelMap.addAttribute("currUser",user);
        return ;
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public String get(@PathVariable Integer id, Model model){

        News news = newsMapper.selectNewsById(id);

        List<Comment> comments = commentsMapper.selectCommentsInNews(id);

        if(comments.isEmpty()) comments = null;

        if(news==null){
            model.addAttribute("err","该新闻不存在");
        }

        model.addAttribute("news",news);

        model.addAttribute("comments",comments);

        return "news";
    }

    @RequestMapping(value = "/edit/{id}",method = RequestMethod.GET)
    public String edit(@PathVariable Integer id, ModelMap model){

        News news = newsMapper.selectNewsById(id);

        if(news==null){
            model.addAttribute("err","该新闻不存在");
        }
        else{
            User user = (User) model.get("currUser");
            if(user==null){
                return "redirect:/news/"+id;
            }
            if(!user.getUserType().hasAdminAuth() &&
                    (!user.getUserType().hasEditAuth() ||
                            !news.getAuthor().equals(user.getUsername())) ){
                return "redirect:/news/"+id;
            }
        }

        model.addAttribute("news",news);

        model.addAttribute("update",true);

        return "edit";
    }
}
